package com.wv.common.exception;

import cn.dev33.satoken.exception.NotPermissionException;
import com.wv.common.result.HttpCodeEnum;
import com.wv.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.stream.Collectors;

@Slf4j
@ControllerAdvice
public class ExceptionCatch {

    /**
     * 处理不可控异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result exception(Exception e) {
        e.printStackTrace();
        log.error("catch exception:{}",e.getMessage());
        return Result.error(HttpCodeEnum.ERROR);
    }

    /**
     * 处理权限不足异常
     * @param e
     * @return
     */
    @ExceptionHandler(NotPermissionException.class)
    @ResponseBody
    public Result exception(NotPermissionException e){
        log.error("catch exception:{}",e.getMessage());
        return Result.error(HttpCodeEnum.PERMISSION_ERROR);
    }




    /**
     * 处理可控异常
     * @param e
     * @return
     */
    @ExceptionHandler(WVException.class)
    @ResponseBody
    public Result exception(WVException e) {
        log.error("catch exception:{}",e);
        return Result.error(e.getHttpCodeEnum());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result exception(MethodArgumentNotValidException e){
        e.printStackTrace();
        log.error("catch exception:{}",e.getMessage());
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
        return Result.error(message);
    }



}
